/*
 * Copyright 2005-2013 dhcc.com.cn. All rights reserved.
 * Support: http://www.dhcc.com.cn
 * License: http://www.dhcc.com.cn/license
 * 
 * JavaScript - Common
 * Version: 3.0
 */

var shopxx = {
    base: "/mango",
    locale: "zh_CN"
};

var setting = {
    priceScale: "2",
    priceRoundType: "roundHalfUp",
    currencySign: "￥",
    currencyUnit: "元",
    uploadImageExtension: "jpg,jpeg,bmp,gif,png",
    uploadFlashExtension: "swf,flv",
    uploadMediaExtension: "swf,flv,mp3,wav,avi,rm,rmvb",
    uploadFileExtension: "zip,rar,7z,doc,docx,xls,xlsx,ppt,pptx"
};

var messages = {
    "shop.message.success": "操作成功",
    "shop.message.error": "操作错误",
    "shop.dialog.ok": "确&nbsp;&nbsp;定",
    "shop.dialog.cancel": "取&nbsp;&nbsp;消",
    "shop.dialog.deleteConfirm": "您确定要删除吗？",
    "shop.dialog.clearConfirm": "您确定要清空吗？",
    "shop.validate.required": "必填",
    "shop.validate.email": "E-mail格式错误",
    "shop.validate.url": "网址格式错误",
    "shop.validate.date": "日期格式错误",
    "shop.validate.dateISO": "日期格式错误",
    "shop.validate.pointcard": "信用卡格式错误",
    "shop.validate.number": "只允许输入数字",
    "shop.validate.digits": "只允许输入零或正整数",
    "shop.validate.minlength": "长度不允许小于{0}",
    "shop.validate.maxlength": "长度不允许大于{0}",
    "shop.validate.rangelength": "长度必须在{0}-{1}之间",
    "shop.validate.min": "不允许小于{0}",
    "shop.validate.max": "不允许大于{0}",
    "shop.validate.range": "必须在{0}-{1}之间",
    "shop.validate.accept": "输入后缀错误",
    "shop.validate.equalTo": "两次输入不一致",
    "shop.validate.remote": "输入错误",
    "shop.validate.integer": "只允许输入整数",
    "shop.validate.positive": "只允许输入正数",
    "shop.validate.negative": "只允许输入负数",
    "shop.validate.decimal": "数值超出了允许范围",
    "shop.validate.pattern": "格式错误",
    "shop.validate.extension": "文件格式错误"
};

// 添加Cookie
function addCookie(name, value, options) {
    if (arguments.length > 1 && name != null) {
        if (options == null) {
            options = {};
        }
        if (value == null) {
            options.expires = -1;
        }
        if (typeof options.expires == "number") {
            var time = options.expires;
            var expires = options.expires = new Date();
            expires.setTime(expires.getTime() + time * 1000);
        }
        document.cookie = encodeURIComponent(String(name)) + "=" + encodeURIComponent(String(value)) + (options.expires ? "; expires=" + options.expires.toUTCString() : "") + (options.path ? "; path=" + options.path : "") + (options.domain ? "; domain=" + options.domain : ""), (options.secure ? "; secure" : "");
    }
}

// 获取Cookie
function getCookie(name) {
    if (name != null) {
        var value = new RegExp("(?:^|; )" + encodeURIComponent(String(name)) + "=([^;]*)").exec(document.cookie);
        return value ? decodeURIComponent(value[1]) : null;
    }
}

// 移除Cookie
function removeCookie(name, options) {
    addCookie(name, null, options);
}

// 货币格式化
function currency(value, showSign, showUnit) {
    if (value != null) {
        var price;
        if (setting.priceRoundType == "roundHalfUp") {
            price = (Math.round(value * Math.pow(10, setting.priceScale)) / Math.pow(10, setting.priceScale)).toFixed(setting.priceScale);
        } else if (setting.priceRoundType == "roundUp") {
            price = (Math.ceil(value * Math.pow(10, setting.priceScale)) / Math.pow(10, setting.priceScale)).toFixed(setting.priceScale);
        } else {
            price = (Math.floor(value * Math.pow(10, setting.priceScale)) / Math.pow(10, setting.priceScale)).toFixed(setting.priceScale);
        }
        if (showSign) {
            price = setting.currencySign + price;
        }
        if (showUnit) {
            price += setting.currencyUnit;
        }
        return price;
    }
}

// 多语言
function message(code) {
    if (code != null) {
        var content = messages[code] != null ? messages[code] : code;
        if (arguments.length == 1) {
            return content;
        } else {
            if ($.isArray(arguments[1])) {
                $.each(arguments[1], function (i, n) {
                    content = content.replace(new RegExp("\\{" + i + "\\}", "g"), n);
                });
                return content;
            } else {
                $.each(Array.prototype.slice.apply(arguments).slice(1), function (i, n) {
                    content = content.replace(new RegExp("\\{" + i + "\\}", "g"), n);
                });
                return content;
            }
        }
    }
}

(function ($) {

    var zIndex = 100;

    // 检测登录
    $.checkLogin = function () {
        var result = false;
        $.ajax({
            url: shopxx.base + "/login/check.jhtml",
            type: "GET",
            dataType: "json",
            cache: false,
            async: false,
            success: function (data) {
                result = data;
            }
        });
        return result;
    }

    // 跳转登录
    $.redirectLogin = function (redirectUrl, message) {
        var href = shopxx.base + "/login.jhtml";
        if (redirectUrl != null) {
            href += "?redirectUrl=" + encodeURIComponent(redirectUrl);
        }
        if (message != null) {
            $.message("warn", message);
            setTimeout(function () {
                location.href = href;
            }, 1000);
        } else {
            location.href = href;
        }
    }

    // 消息框
    var $message;
    var messageTimer;
    $.message = function () {
        var message = {};
        if ($.isPlainObject(arguments[0])) {
            message = arguments[0];
        } else if (typeof arguments[0] === "string" && typeof arguments[1] === "string") {
            message.type = arguments[0];
            message.content = arguments[1];
        } else {
            return false;
        }

        if (message.type == null || message.content == null) {
            return false;
        }

        if ($message == null) {
            $message = $('<div class="xxMessage"><div class="messageContent message' + message.type + 'Icon"><\/div><\/div>');
            if (!window.XMLHttpRequest) {
                $message.append('<iframe class="messageIframe"><\/iframe>');
            }
            $message.appendTo("body");
        }

        $message.children("div").removeClass("messagewarnIcon messageerrorIcon messagesuccessIcon").addClass("message" + message.type + "Icon").html(message.content);
        $message.css({"margin-left": -parseInt($message.outerWidth() / 2), "z-index": zIndex++}).show();

        clearTimeout(messageTimer);
        messageTimer = setTimeout(function () {
            $message.hide();
        }, 3000);
        return $message;
    }

    // 令牌
    $(document).ajaxSend(function (event, request, settings) {
        if (!settings.crossDomain && settings.type != null && settings.type.toLowerCase() == "post") {
            var token = getCookie("token");
            if (token != null) {
                request.setRequestHeader("token", token);
            }
        }
    });

    $(document).ajaxComplete(function (event, request, settings) {
        var loginStatus = request.getResponseHeader("loginStatus");
        var tokenStatus = request.getResponseHeader("tokenStatus");

        if (loginStatus == "accessDenied") {
            $.redirectLogin(location.href, "请登录后再进行操作");
        } else if (tokenStatus == "accessDenied") {
            var token = getCookie("token");
            if (token != null) {
                $.extend(settings, {
                    global: false,
                    headers: {token: token}
                });
                $.ajax(settings);
            }
        }
    });

})(jQuery);

// 令牌
$().ready(function () {

    $("form").submit(function () {
        var $this = $(this);
        if ($this.attr("method") != null && $this.attr("method").toLowerCase() == "post" && $this.find("input[name='token']").size() == 0) {
            var token = getCookie("token");
            if (token != null) {
                $this.append('<input type="hidden" name="token" value="' + token + '" \/>');
            }
        }
    });

});

// 验证消息
if ($.validator != null) {
    $.extend($.validator.messages, {
        required: message("shop.validate.required"),
        email: message("shop.validate.email"),
        url: message("shop.validate.url"),
        date: message("shop.validate.date"),
        dateISO: message("shop.validate.dateISO"),
        pointcard: message("shop.validate.pointcard"),
        number: message("shop.validate.number"),
        digits: message("shop.validate.digits"),
        minlength: $.validator.format(message("shop.validate.minlength")),
        maxlength: $.validator.format(message("shop.validate.maxlength")),
        rangelength: $.validator.format(message("shop.validate.rangelength")),
        min: $.validator.format(message("shop.validate.min")),
        max: $.validator.format(message("shop.validate.max")),
        range: $.validator.format(message("shop.validate.range")),
        accept: message("shop.validate.accept"),
        equalTo: message("shop.validate.equalTo"),
        remote: message("shop.validate.remote"),
        integer: message("shop.validate.integer"),
        positive: message("shop.validate.positive"),
        negative: message("shop.validate.negative"),
        decimal: message("shop.validate.decimal"),
        pattern: message("shop.validate.pattern"),
        extension: message("shop.validate.extension")
    });

    $.validator.setDefaults({
        errorClass: "fieldError",
        ignore: ".ignore",
        ignoreTitle: true,
        errorPlacement: function (error, element) {
            var fieldSet = element.closest("span.fieldSet");
            if (fieldSet.size() > 0) {
                error.appendTo(fieldSet);
            } else {
                error.insertAfter(element);
            }
        },
        submitHandler: function (form) {
            $(form).find(":submit").prop("disabled", true);
            form.submit();
        }
    });
}